﻿using System.Collections;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.UI;

namespace Game.UI.Example
{
    public class PlayerStatusBar : MonoBehaviour
    {
        public enum PlayerStatus
        {
            HP,
            MP,
            PP
        }

        #region Inspector

        public PlayerStatus playerStatus;
        /// <summary>
        /// 开启延迟条效果
        /// </summary>
        public bool enableDelayBarEffect;
        [ShowIf("enableDelayBarEffect")]
        public float lerpTime = 5f;

        #endregion
        
        private Slider _statusSlider;
        private RectTransform _statusSliderRectTransform;
        private RectTransform _fillAfter;

        #region System Methods

        private void Awake()
        {
            _statusSlider = GetComponentInChildren<Slider>();
            _statusSliderRectTransform = _statusSlider.transform as RectTransform;
            _fillAfter = _statusSlider.fillRect.parent.Find("Fill_After") as RectTransform;
        }

        private void Start()
        {
            _statusSlider.onValueChanged.AddListener(OnStatusChange);
        }

        #endregion

        public void SetValue(float newValue, float maxValue)
        {
            _statusSlider.value = Mathf.Clamp01(newValue / maxValue);
        }
        
        private void OnStatusChange(float value)
        {
            
            
            if (enableDelayBarEffect)
            {
                if (_delayChangeFillCoroutine != null)
                    StopCoroutine(_delayChangeFillCoroutine);
                _delayChangeFillCoroutine = StartCoroutine(DelayChangeFill(value));
            }
        }

        private Coroutine _delayChangeFillCoroutine;
        private IEnumerator DelayChangeFill(float targetX)
        {
            while (!Mathf.Approximately(_fillAfter.anchorMax.x, targetX))
            {
                Vector2 anchorMax = _fillAfter.anchorMax;
                anchorMax.x = Mathf.Lerp(anchorMax.x, targetX,  lerpTime * Time.deltaTime);
                _fillAfter.anchorMax = anchorMax;
                yield return null;
            }

            _fillAfter.anchorMax = new Vector2(targetX, _fillAfter.anchorMax.y);
        }
    }
}